package com.kakaxi.mybilibili.module.home;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kakaxi.mybilibili.R;
import com.kakaxi.mybilibili.base.MyApplication;
import com.kakaxi.mybilibili.base.NavigationActivity;
import com.kakaxi.mybilibili.bean.EventBusObject;
import com.kakaxi.mybilibili.bean.MemberBean;
import com.kakaxi.mybilibili.module.search.view.SearchActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends NavigationActivity {

    @BindView(R.id.llayout_main_toolbar_content)
    LinearLayout toolBarContent;

    @BindView(R.id.txt_main_toolbar_name)
    TextView nameTxt;

    @BindView(R.id.civ_main_toolbar_face)
    CircleImageView faceImg;

    /** 主界面滑动视图控件 **/
    private ViewPager mMainViewPager;

    /** 标签标题数组 **/
    private int[] mTabTitleArray = {
            R.string.tab_main_live, R.string.tab_main_advice, R.string.tab_main_drama, R.string
            .tab_main_category,
            R.string.tab_main_concern, R.string.tab_main_find
    };

    @Override
    protected int getCurrentMenuItemId() {
        return R.menu.menu_nav;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void setupViews() {
        ButterKnife.bind(this);

        if (getToolBar() != null) {
            // 添加工具栏的侧滑菜单按钮,创建一个标题栏与抽屉的关联开关
//            ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,
// getDrawerLayout(),
//                    getToolBar(), R.string.navigation_drawer_open, R
//                    .string.navigation_drawer_close);
            //同步抽屉的指示器状态，只有加这一句抽屉的开关才会改变Toolbar上的NavigationIcon图标
//            drawerToggle.syncState();
        }

        // 工具栏初始化
        toolBarContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDrawerLayout().openDrawer(GravityCompat.START);
            }
        });

        // 添加标签
        final TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout_main_top_tab);
        for (int title : mTabTitleArray) {
            tabLayout.addTab(tabLayout.newTab().setText(title));
        }

        // 装配滑动视图
        mMainViewPager = (ViewPager) findViewById(R.id.vp_main);
        mMainViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                // 根据位置创建碎片
                return MainFragmentFactory.createFragment(position);
            }

            @Override
            public int getCount() {
                return MainFragmentFactory.FRAGMENT_COUNT;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return getString(mTabTitleArray[position]);
            }
        });
        tabLayout.setupWithViewPager(mMainViewPager);

        // 移动到推荐标签页
        mMainViewPager.setCurrentItem(1);
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);

        // 取消工具栏的标题
        setTitle("");
        // 更新工具栏用户信息
        updateToolBarUserInfo();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 从碎片控制标签的切换
     * (推荐碎片中调用)
     *
     * @param object 数据
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onControlViewPagerEventBus(EventBusObject object) {
        if (object.getEvent() == EventBusObject.EVENT_MAIN_ACT_TURN_PAGE) {
            // 跳转到对应的标签
            Integer pos = (Integer) object.getData();
            mMainViewPager.setCurrentItem(pos, true);
        }
    }

    /**
     * 更新工具栏的用户信息
     *
     * @param object 事件巴士对象
     */
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onUpdateToolBarEventBus(EventBusObject object) {
        if (object.getEvent() == EventBusObject.EVENT_MAIN_ACT_UPDATE_USER_INFO) {
            updateToolBarUserInfo();
            updateNavHeaderUserInfo();
        }
    }

    /**
     * 更新工具栏上面的用户信息
     */
    private void updateToolBarUserInfo() {
        MemberBean memberBean = ((MyApplication) getApplication()).getMemberBean();
        if (memberBean != null && memberBean.getMid() != null) {
            String username = memberBean.getName();
            String face = memberBean.getFace();
            if (username != null) nameTxt.setText(username);
            if (face != null) {
                Glide.with(getBaseContext()).load(face).crossFade().into(faceImg);
            }
        }
    }

    /**
     * 清除工具栏上面的用户信息
     */
    private void clearToolBarUserInfo() {
        nameTxt.setText("未登录");
        faceImg.setImageDrawable(ActivityCompat.getDrawable(getBaseContext(), R.drawable
                .bili_default_avatar));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_search:
                Bundle bundle = new Bundle();
                bundle.putInt(SearchActivity.EXTRA_TYPE, SearchActivity.TYPE_VIDEO);
                goActivity(SearchActivity.class, bundle);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
